package com.haoc.lostandfound.auth;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.haoc.lostandfound.R;
import com.haoc.lostandfound.activity.MainActivity;
import com.haoc.lostandfound.utils.Myutils;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectAuthCredential;
import com.huawei.agconnect.auth.EmailAuthProvider;
import com.huawei.agconnect.auth.PhoneAuthProvider;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.auth.VerifyCodeSettings;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;

public class LoginActivity extends Activity implements View.OnClickListener {
    private TextView accountTv;
    private EditText accountEdit;
    private EditText passwordEdit;
    private EditText verifyCodeEdit;
    private LinearLayout galleryLayout;
    private static Type type = Type.EMAIL;
    public static LoginActivity loginActivity = null;
    Button send;
    private String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginActivity = this;
        if (AGConnectAuth.getInstance().getCurrentUser() != null) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
        initView();
        ActivityCompat.requestPermissions(this, permissions, 1);
    }

    private void initView() {
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.white));
        accountTv = findViewById(R.id.tv_account);
        accountEdit = findViewById(R.id.et_account);
        passwordEdit = findViewById(R.id.et_password);
        verifyCodeEdit = findViewById(R.id.et_verify_code);
        RadioGroup radioGroup = findViewById(R.id.radiogroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radiobutton_email:
                        type = Type.EMAIL;
                        break;
                    case R.id.radiobutton_phone:
                        type = Type.PHONE;
                        break;
                }
                updateView();
            }
        });

        Button loginBtn = findViewById(R.id.btn_login);
        loginBtn.setOnClickListener(this);
        Button registerBtn = findViewById(R.id.btn_register);
        registerBtn.setOnClickListener(this);
        send = findViewById(R.id.btn_send);
        send.setOnClickListener(this);
        galleryLayout = findViewById(R.id.id_gallery);
        findViewById(R.id.btn_login_anonymous).setOnClickListener(this);
        initThird();
    }

    private void initThird() {
        int[] ids = getResources().getIntArray(R.array.ids);
        TypedArray typedArray = getResources().obtainTypedArray(R.array.ids);//获得任意类型
        String[] names = getResources().getStringArray(R.array.names);
        LayoutInflater inflater = LayoutInflater.from(this);
        for (int i = 0; i < ids.length; i++) {
            View view = inflater.inflate(R.layout.layout_img, galleryLayout, false);
            ImageView img = view.findViewById(R.id.image);
            img.setImageResource(typedArray.getResourceId(i, R.mipmap.huawei));
            TextView text = view.findViewById(R.id.text);
            text.setText(names[i]);
            view.setOnClickListener(new ThirdListener(names[i]));
            galleryLayout.addView(view);
        }
    }

    public class ThirdListener implements View.OnClickListener {
        private String name;

        ThirdListener(String name) {
            this.name = name;
        }

        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (name) {
                case "华为帐号":
                    intent = new Intent(LoginActivity.this, HWIDActivity.class);
                    break;
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    }

    private void updateView() {
        if (type == Type.EMAIL) {
            accountTv.setText(R.string.login_email);
        } else {
            accountTv.setText(R.string.phone_number);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.btn_register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                intent.putExtra("registerType", type);
                startActivity(intent);
                break;
            case R.id.btn_send:
                sendVerificationCode();
                break;
            case R.id.btn_login_anonymous:
                loginAnonymous();
                break;
        }
    }

    private void sendVerificationCode() {
        if (type == Type.EMAIL) {
            String email = accountEdit.getText().toString().trim();
            Myutils.sendVerificationCodeByEmail(LoginActivity.this, send, email, VerifyCodeSettings.ACTION_REGISTER_LOGIN);
        } else {
            String phoneNumber = accountEdit.getText().toString().trim();
            Myutils.sendVerificationCodeByPhoneNumber(LoginActivity.this, send, phoneNumber, VerifyCodeSettings.ACTION_REGISTER_LOGIN);
        }
    }

    private void login() {
        if (type == Type.EMAIL) {
            String email = accountEdit.getText().toString().trim();
            String password = passwordEdit.getText().toString().trim();
            String verifyCode = verifyCodeEdit.getText().toString().trim();
            AGConnectAuthCredential credential;
            if (TextUtils.isEmpty(verifyCode)) {
                credential = EmailAuthProvider.credentialWithPassword(email, password);
            } else {
                //如果您没有密码，密码参数可以为空
                credential = EmailAuthProvider.credentialWithVerifyCode(email, password, verifyCode);
            }
            signIn(credential);
        } else {
            String phoneNumber = accountEdit.getText().toString().trim();
            String password = passwordEdit.getText().toString().trim();
            String verifyCode = verifyCodeEdit.getText().toString().trim();
            AGConnectAuthCredential credential;
            if (TextUtils.isEmpty(verifyCode)) {
                credential = PhoneAuthProvider.credentialWithPassword("86", phoneNumber, password);
            } else {
                //如果您没有密码，密码参数可以为空
                credential = PhoneAuthProvider.credentialWithVerifyCode("86", phoneNumber, password, verifyCode);
            }
            signIn(credential);
        }
    }

    private void signIn(AGConnectAuthCredential credential) {
        AGConnectAuth.getInstance().signIn(credential)
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "登录失败:" + e, Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void loginAnonymous() {
        // 匿名登录
        AGConnectAuth.getInstance().signInAnonymously()
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "匿名登录失败:" + e, Toast.LENGTH_LONG).show();
                    }
                });
    }

    enum Type {
        EMAIL,
        PHONE
    }
}